<template>
  <div class="sql-formatter">
    <button @click="returnFn" class="btn btn-primary retrunBUtton">
      <i class="icon">⚡</i> 返回
    </button>
    <div class="container">
      <header class="tool-header">
        <h1>SQL 格式化工具</h1>
        <p class="subtitle">美化您的SQL代码，提高可读性</p>
      </header>

      <div class="tool-content">
        <div class="editor-section">
          <div class="input-panel">
            <div class="panel-header">
              <label>输入SQL代码：</label>
              <div class="action-buttons">
                <button class="format-btn" @click="formatSQL" :disabled="!inputSQL">
                  {{ isFormatted ? '重新格式化' : '格式化SQL' }}
                </button>
                <button class="clear-btn" @click="clearInput">清空</button>
              </div>
            </div>
            <textarea
              v-model="inputSQL"
              placeholder="粘贴SQL代码到这里..."
              rows="12"
              class="sql-input"
              :class="{ formatted: isFormatted }"
            ></textarea>
          </div>

          <div class="output-panel">
            <div class="panel-header">
              <label>格式化结果：</label>
              <div class="action-buttons">
                <button class="copy-btn" @click="copyOutput" :disabled="!formattedSQL">
                  {{ copyButtonText }}
                </button>
              </div>
            </div>
            <pre
              class="formatted-code"
            ><code>{{ formattedSQL || '格式化后的SQL将显示在这里' }}</code></pre>
          </div>
        </div>

        <div class="options-section">
          <h3>格式化选项</h3>
          <div class="options-grid">
            <div class="option-group">
              <label>缩进类型：</label>
              <div class="radio-group">
                <label class="radio-label">
                  <input type="radio" v-model="options.indentType" value="spaces" />
                  <span class="radio-custom"></span>
                  空格
                </label>
                <label class="radio-label">
                  <input type="radio" v-model="options.indentType" value="tabs" />
                  <span class="radio-custom"></span>
                  制表符
                </label>
              </div>
            </div>

            <div class="option-group">
              <label>缩进大小：</label>
              <select v-model="options.indentSize">
                <option value="2">2</option>
                <option value="4">4</option>
                <option value="8">8</option>
              </select>
            </div>

            <div class="option-group">
              <label>关键字大小写：</label>
              <select v-model="options.keywordCase">
                <option value="upper">大写</option>
                <option value="lower">小写</option>
                <option value="preserve">保持原样</option>
              </select>
            </div>

            <div class="option-group">
              <label class="checkbox-label">
                <input type="checkbox" v-model="options.alignColumns" />
                <span class="checkmark"></span>
                对齐列名
              </label>
            </div>

            <div class="option-group">
              <label class="checkbox-label">
                <input type="checkbox" v-model="options.breakBeforeComma" />
                <span class="checkmark"></span>
                逗号前换行
              </label>
            </div>

            <div class="option-group">
              <label class="checkbox-label">
                <input type="checkbox" v-model="options.uppercaseFunctions" />
                <span class="checkmark"></span>
                函数名大写
              </label>
            </div>
          </div>
        </div>

        <div class="info-section">
          <h3>SQL格式化说明</h3>
          <p>
            格式化工具可以帮助您整理SQL代码，使其具有一致的缩进和结构，提高代码的可读性和可维护性。支持SELECT、INSERT、UPDATE、DELETE、CREATE等常见SQL语句。
          </p>
        </div>
      </div>

      <footer class="tool-footer">
        <p>© 2025 SQL格式化工具</p>
      </footer>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
const inputSQL = ref('')
const formattedSQL = ref('')
const isFormatted = ref(false)
const copyButtonText = ref('复制代码')

const options = ref({
  indentType: 'spaces',
  indentSize: 2,
  keywordCase: 'upper',
  alignColumns: true,
  breakBeforeComma: false,
  uppercaseFunctions: true
})

const SQL_KEYWORDS = [
  'SELECT', 'FROM', 'WHERE', 'INSERT', 'INTO', 'VALUES', 'UPDATE', 'SET',
  'DELETE', 'CREATE', 'TABLE', 'ALTER', 'DROP', 'JOIN', 'LEFT', 'RIGHT',
  'INNER', 'OUTER', 'ON', 'GROUP BY', 'ORDER BY', 'HAVING', 'LIMIT',
  'OFFSET', 'UNION', 'ALL', 'DISTINCT', 'AS', 'AND', 'OR', 'NOT', 'IN',
  'BETWEEN', 'LIKE', 'IS', 'NULL', 'TRUE', 'FALSE'
]

const SQL_FUNCTIONS = [
  'COUNT', 'SUM', 'AVG', 'MIN', 'MAX', 'COALESCE', 'NULLIF', 'CASE',
  'WHEN', 'THEN', 'ELSE', 'END', 'CAST', 'EXTRACT', 'DATE_PART',
  'UPPER', 'LOWER', 'TRIM', 'LTRIM', 'RTRIM', 'LENGTH', 'SUBSTRING',
  'CONCAT', 'REPLACE', 'ROUND', 'CEIL', 'FLOOR', 'ABS', 'NOW', 'CURRENT_DATE'
]
const Router = useRouter()
const returnFn = () => {
  Router.go(-1)
}
const formatSQL = () => {
  if (!inputSQL.value.trim()) {
    formattedSQL.value = ''
    isFormatted.value = false
    return
  }

  try {
    let sql = inputSQL.value
    let indentLevel = 0
    const indentChar = options.value.indentType === 'tabs' ? '\t' : ' '.repeat(parseInt(options.value.indentSize))
    const lines = sql.split('\n')
    let result = []
    let inParentheses = 0
    let inString = false
    let stringChar = ''
    let currentLine = ''
    let lastToken = ''

    const processToken = (token) => {
      const upperToken = token.toUpperCase().trim()
      const isKeyword = SQL_KEYWORDS.includes(upperToken)
      const isFunction = SQL_FUNCTIONS.includes(upperToken)

      if (isKeyword) {
        token = options.value.keywordCase === 'upper' ? token.toUpperCase() :
          options.value.keywordCase === 'lower' ? token.toLowerCase() : token
      }

      if (isFunction && options.value.uppercaseFunctions) {
        token = token.toUpperCase()
      }

      if (upperToken === 'SELECT' || upperToken === 'FROM' || upperToken === 'WHERE' ||
        upperToken === 'ORDER BY' || upperToken === 'GROUP BY' || upperToken === 'HAVING') {
        if (currentLine.trim()) {
          result.push(currentLine)
        }
        currentLine = indentChar.repeat(indentLevel) + token
      } else if (upperToken === 'INSERT' || upperToken === 'UPDATE' || upperToken === 'DELETE') {
        if (currentLine.trim()) {
          result.push(currentLine)
        }
        currentLine = indentChar.repeat(indentLevel) + token
        indentLevel++
      } else if (upperToken === 'VALUES') {
        if (currentLine.trim()) {
          result.push(currentLine)
        }
        currentLine = indentChar.repeat(indentLevel) + token
      } else if (upperToken === 'AND' || upperToken === 'OR') {
        if (currentLine.trim()) {
          result.push(currentLine)
        }
        currentLine = indentChar.repeat(indentLevel) + token
      } else if (token === '(') {
        inParentheses++
        currentLine += token
        if (options.value.breakBeforeComma) {
          result.push(currentLine)
          currentLine = indentChar.repeat(indentLevel + 1)
        }
      } else if (token === ')') {
        inParentheses--
        if (currentLine.trim() && !currentLine.trim().endsWith('(')) {
          result.push(currentLine)
          currentLine = indentChar.repeat(indentLevel) + token
        } else {
          currentLine += token
        }
      } else if (token === ',') {
        if (options.value.breakBeforeComma) {
          result.push(currentLine)
          currentLine = indentChar.repeat(indentLevel + inParentheses) + token
        } else {
          currentLine += token
          if (inParentheses > 0 && options.value.alignColumns) {
            result.push(currentLine)
            currentLine = indentChar.repeat(indentLevel + inParentheses)
          }
        }
      } else {
        if (currentLine && !currentLine.endsWith(' ') && token !== ' ') {
          currentLine += ' '
        }
        currentLine += token
      }

      lastToken = upperToken
    }

    for (let line of lines) {
      const tokens = tokenizeSQL(line)
      for (let token of tokens) {
        processToken(token)
      }
    }

    if (currentLine.trim()) {
      result.push(currentLine)
    }

    formattedSQL.value = result.join('\n')
    isFormatted.value = true
  } catch (error) {
    console.error('格式化错误:', error)
    formattedSQL.value = '格式化出错，请检查SQL代码语法'
    isFormatted.value = false
  }
}

const tokenizeSQL = (sql) => {
  const tokens = []
  let currentToken = ''
  let inString = false
  let stringChar = ''
  let inComment = false
  let commentType = '' // '--' or '/*'

  for (let i = 0; i < sql.length; i++) {
    const char = sql[i]
    const nextChar = sql[i + 1]

    if (inComment) {
      currentToken += char
      if (commentType === '--' && char === '\n') {
        inComment = false
        commentType = ''
        tokens.push(currentToken)
        currentToken = ''
      } else if (commentType === '/*' && char === '*' && nextChar === '/') {
        currentToken += nextChar
        i++ // 跳过下一个字符
        inComment = false
        commentType = ''
        tokens.push(currentToken)
        currentToken = ''
      }
      continue
    }

    if (inString) {
      currentToken += char
      if (char === stringChar && sql[i - 1] !== '\\') {
        inString = false
        tokens.push(currentToken)
        currentToken = ''
      }
      continue
    }

    if (char === '-' && nextChar === '-') {
      if (currentToken) {
        tokens.push(currentToken)
        currentToken = ''
      }
      inComment = true
      commentType = '--'
      currentToken = char
      continue
    }

    if (char === '/' && nextChar === '*') {
      if (currentToken) {
        tokens.push(currentToken)
        currentToken = ''
      }
      inComment = true
      commentType = '/*'
      currentToken = char
      continue
    }

    if (char === "'" || char === '"') {
      if (currentToken) {
        tokens.push(currentToken)
        currentToken = ''
      }
      inString = true
      stringChar = char
      currentToken = char
      continue
    }

    if (/\s/.test(char)) {
      if (currentToken) {
        tokens.push(currentToken)
        currentToken = ''
      }
      tokens.push(' ')
      continue
    }

    if (/[(),;]/.test(char)) {
      if (currentToken) {
        tokens.push(currentToken)
        currentToken = ''
      }
      tokens.push(char)
      continue
    }

    currentToken += char
  }

  if (currentToken) {
    tokens.push(currentToken)
  }

  return tokens.filter(token => token !== '')
}

const copyOutput = async () => {
  if (!formattedSQL.value) return

  try {
    await navigator.clipboard.writeText(formattedSQL.value)
    copyButtonText.value = '已复制!'
    setTimeout(() => {
      copyButtonText.value = '复制代码'
    }, 2000)
  } catch (err) {
    const textArea = document.createElement('textarea')
    textArea.value = formattedSQL.value
    document.body.appendChild(textArea)
    textArea.select()
    try {
      document.execCommand('copy')
      copyButtonText.value = '已复制!'
      setTimeout(() => {
        copyButtonText.value = '复制代码'
      }, 2000)
    } catch (err2) {
      copyButtonText.value = '复制失败'
      setTimeout(() => {
        copyButtonText.value = '复制代码'
      }, 2000)
    }
    document.body.removeChild(textArea)
  }
}

const clearInput = () => {
  inputSQL.value = ''
  formattedSQL.value = ''
  isFormatted.value = false
}

watch(inputSQL, (newValue) => {
  if (newValue && isFormatted.value) {
    isFormatted.value = false
  }
})

watch(options, () => {
  if (inputSQL.value && isFormatted.value) {
    formatSQL()
  }
}, { deep: true })
</script>

<style scoped>
.btn {
  padding: 8px 15px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 20px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 5px;
  transition: all 0.3s ease;
}

.btn-primary {
  background: linear-gradient(to right, #1a2a6c, #b21f1f);
  color: white;
}
.retrunBUtton {
  position: absolute;
  top: 100px;
  right: 100px;
}
.sql-formatter {
  min-height: 100vh;
  position: relative;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  background: white;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
}

.tool-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 30px;
  text-align: center;
  border-radius: 12px 12px 0 0;
}

.tool-header h1 {
  margin: 0 0 10px 0;
  font-size: 2.2em;
}

.subtitle {
  margin: 0;
  opacity: 0.9;
  font-size: 1.1em;
}

.tool-content {
  padding: 30px;
}

.editor-section {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 30px;
}

.input-panel,
.output-panel {
  display: flex;
  flex-direction: column;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.panel-header label {
  font-weight: 600;
  color: #333;
  font-size: 20px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.format-btn,
.clear-btn,
.copy-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  font-size: 18px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
}

.format-btn {
  background: linear-gradient(to right, #4caf50, #45a049);
  color: white;
}

.format-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(76, 175, 80, 0.3);
}

.format-btn:disabled {
  background: #cccccc;
  cursor: not-allowed;
}

.clear-btn {
  background: #ff9800;
  color: white;
}

.clear-btn:hover {
  background: #f57c00;
  transform: translateY(-2px);
}

.copy-btn {
  background: #2196f3;
  color: white;
}

.copy-btn:hover:not(:disabled) {
  background: #1976d2;
  transform: translateY(-2px);
}

.copy-btn:disabled {
  background: #cccccc;
  cursor: not-allowed;
}

.sql-input {
  padding: 15px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  font-size: 18px;
  font-family: 'Courier New', monospace;
  resize: vertical;
  transition: border-color 0.3s;
  background: #f8f9fa;
  line-height: 1.5;
  height: 300px;
}

.sql-input:focus {
  outline: none;
  border-color: #667eea;
}

.sql-input.formatted {
  border-color: #4caf50;
}

.formatted-code {
  height: 300px;
  padding: 15px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  background: #2d3748;
  color: #e2e8f0;
  font-family: 'Courier New', monospace;
  font-size: 22px;
  overflow: auto;
  white-space: pre-wrap;
  line-height: 1.5;
  margin: 0;
}

.options-section {
  margin-bottom: 30px;
}

.options-section h3 {
  margin-bottom: 15px;
  color: #333;
  font-size: 22px;
}

.options-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
}

.option-group {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.option-group label {
  font-weight: 600;
  color: #555;
  font-size: 18px;
}

.radio-group {
  display: flex;
  gap: 20px;
}

.radio-label,
.checkbox-label {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  font-weight: normal;
}

.radio-label input,
.checkbox-label input {
  display: none;
}

.radio-custom {
  width: 18px;
  height: 18px;
  border: 2px solid #ddd;
  border-radius: 50%;
  position: relative;
  transition: all 0.3s;
}

.radio-label input:checked + .radio-custom {
  border-color: #667eea;
}

.radio-label input:checked + .radio-custom::after {
  content: '';
  width: 8px;
  height: 8px;
  background: #667eea;
  border-radius: 50%;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.checkmark {
  width: 18px;
  height: 18px;
  border: 2px solid #ddd;
  border-radius: 3px;
  position: relative;
  transition: all 0.3s;
}

.checkbox-label input:checked + .checkmark {
  background: #667eea;
  border-color: #667eea;
}

.checkbox-label input:checked + .checkmark::after {
  content: '✓';
  position: absolute;
  color: white;
  font-size: 16px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

select {
  padding: 8px 12px;
  border: 2px solid #e0e0e0;
  border-radius: 6px;
  font-size: 16px;
  max-width: 200px;
}

select:focus {
  outline: none;
  border-color: #667eea;
}

.info-section {
  background-color: #e3f2fd;
  border-left: 4px solid #2196f3;
  padding: 15px;
  border-radius: 0 8px 8px 0;
}

.info-section h3 {
  color: #1565c0;
  margin-bottom: 10px;
  font-size: 18px;
}

.info-section p {
  color: #424242;
  line-height: 1.6;
  font-size: 18px;
  margin: 0;
}

.tool-footer {
  text-align: center;
  padding: 20px;
  color: #757575;
  font-size: 18px;
  border-top: 1px solid #e0e0e0;
}

@media (max-width: 768px) {
  .editor-section {
    grid-template-columns: 1fr;
  }

  .options-grid {
    grid-template-columns: 1fr;
  }

  .action-buttons {
    flex-direction: column;
  }

  .radio-group {
    flex-direction: column;
    gap: 10px;
  }
}
</style>